
function injectCustomJs (jsPath) {
  jsPath = jsPath || './js/injectJs.js'
  var temp = document.createElement('script')
  temp.setAttribute('type', 'text/javascript')
  // 获得的地址类似：chrome-extension://ihcokhadfjfchaeagdoclpnjdiokfakg/js/inject.js
  temp.src = chrome.extension.getURL(jsPath)
  temp.onload = function () {
    // 放在页面不好看，执行完后移除掉
    this.parentNode.removeChild(this)
  }
  document.head.appendChild(temp)
}
// window.addEventListener('message', function (message) {
//   console.log('message', message)
//   if (message.data.action == 'londed') {
//     layer = JSON.parse(message.data.layer)
//   }
// }, false)
injectCustomJs()
function showMsg (msg) {
  window.postMessage({ 'action': 'layer', 'msg': '插件提示：' + msg }, '*')
}
function send (winid, num, type) {
  $.ajax({
    url: 'https://www.vipdat.com/app/index.php?i=25&c=entry&p=centerbtc&do=member&m=sz_yi',
    type: 'POST',
    dataType: 'json',
    data: {
      'num': num,
      'op': 'buybtc',
      'winid': winid,
      'login_type': type || 1
    },
    success: function (json) {
      if (json.status == 1) {
        showMsg(json.result)
        window.location.href = ''
      }
      if (json.status == 109) {
        $('#myform1').hide()
        $('#timer1').hide()
      } else {
        showMsg(json.result)
      }
    },
    error: function (result) {
      showMsg('参与不成功,请检查网络')
    }
  })
}

setTimeout(function () {
  var isdo = false
  var isLogin = true
  var isloaded = false
  var nativeLogin = false
  var canFlash = false
  var isReSub = false
  var isWorking = false
  var subMin = 0.002
  var loginType = 1
  var sendAuto = true
  var yue = 0.000000001
  var isTrySub = false
  $(function () {
    var isCanuser = false
    var $__this = null
    var youhave = $('.p_zc01').parent().find('h4').html() - 0
    function initButton () {
      var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver// 浏览器兼容
      var config = {attributes: true}// 配置对象 , childList: true
      $('.btn.btn_bg').each(function () {
        var _this = $(this)
        var observer = new MutationObserver(function (mutations) { // 构造函数回调
          mutations.forEach(function (record) {
            if (record.type == 'attributes') { // 监听属性
              if (_this.attr('disabled') == 'disabled') {
                // 还是禁止的
              } else {
                // 已经开始了
                initKey(_this)
              }
            }
          })
        })
        if (_this.closest('form').attr('style') != 'display:none' && _this.attr('disabled') != 'disabled') {
          $__this = _this
          isCanuser = true
        }
        observer.observe(_this[0], config)
      })
    }
    initButton()
    var $this = null
    function initKey (_this) {
      var key = _this.attr('id').split('btn_sub')[1]
      console.log('key', key)
      goDoIt(key)
    }
    function goDoIt (key) {
      console.log('isWorking', isWorking, isLogin)
      if (isLogin && isWorking) {
        console.log('key', key)
        inituser(key)
      }
    }
    function inituser (index) {
      var $this = $('#btn_sub' + index)
      var zimu = ['', 'B', 'C']
      var formKey = zimu[index - 1]
      // youhave = $('.p_zc01').parent().find('h4').html() - 0
      $('body,html').animate({
        scrollTop: $('#myform' + index).offset().top // 让body的scrollTop等于pos的top，就实现了滚动
      }, 0)
      // formKey = parseInt($this.data('id'))
      var investNumber = 0
      // 单次 最多
      var maxNumber = $('#service_number' + formKey).val()
      // var isTrySubjectFlag = true

      if (yue > youhave && !isTrySub) {
        showMsg('本次已经提交成功了，已经停止再次提交')
        console.log('本次已经提交成功了，已经停止再次提交,提交前：' + yue + '，提交后:' + youhave)
        return false
      }
      if (yue > 0.000000001) {
        investNumber = Math.min(yue, youhave)
      } else {
        investNumber = youhave
      }
      investNumber = Math.min(maxNumber, investNumber)
      // 好像是盘总数剩余
      // var surplus_number = $('#surplus_number' + formKey).val()
      // investNumber = Math.min(surplus_number, investNumber)
      // 必须大于最小
      var minNumber = $('#final_number' + formKey).val() || 0
      // if (minNumber < investNumber) {
      //   investNumber = Math.max(minNumber, investNumber)
      // }
      console.log('investNumber', investNumber)
      console.log('investNumber', investNumber)
      if (investNumber - 0 >= minNumber && investNumber - 0 >= subMin) {
        $('#num' + (index == 1 ? '' : index)).val(investNumber)
        chrome.runtime.sendMessage({
          action: 'beginSub',
          type: 1
        }, function (response) {
          if (response.state == 'beginSub:ok') {
            if (sendAuto) {
              var winid = $this.attr('onclick').split('(')[1].split(')')[0] - 0
              sendByAuto(winid, investNumber)
            } else {
              setTimeout(function () {
                $this.trigger('click')
                setTimeout(function () {
                  // $this.removeAttr('disabled')
                  $this.trigger('click')
                  if (isReSub) {
                    doReflash(500)
                  }
                }, 200)
              }, 50)
            }
          }
        })
      } else {
        $('#num' + (index == 1 ? '' : index)).parent().append("<div style='color:red;'>您的余额：" + investNumber + "'币;余额不足'</div>")
      }
    }
    function sendByAuto (winid, num) {
      // window.postMessage({
      //   action: 'send',
      //   loginType: loginType,
      //   num: num,
      //   winid: winid
      // }, '*')
      // chrome.runtime.sendMessage({
      //   action: 'send',
      //   loginType: loginType,
      //   num: num,
      //   winid: winid
      // }, function (response) {

      // })
      send(winid, num, loginType)
    }
    function initNativeLogin (type, addr) {
      $('.login_but ul li').eq(type - 1).trigger('click')
      $('#address').val(addr)
      setTimeout(function () {
        $('.binding_but').trigger('click')
      }, 100)
    }
    isRunning()
    function addLis () {
      chrome.runtime.onMessage.addListener(
        function (request, sender, sendResponse) {
          if (request.action == 'begin' && !isdo && canFlash) {
            isWorking = true
            running()
            if (!isCanuser) {
              doReflash(request.ping)
            }
            sendResponse({state: 'begin:ok', isStop: !!isCanuser})
            isdo = true
          }
          if (request.action == 'stratWork') {
            isWorking = request.isWorking
            sendAuto = request.sendAuto
            console.log('isWorking', request)
            sendResponse({state: 'stratWork:ok'})
            running()
          }
          if (request.action == 'nativeLogin' && !isdo) {
            initNativeLogin(request.type, request.addr)
            sendResponse({state: 'nativeLogin:ok', isStop: !!isCanuser})
            isdo = true
          }
          if (request.action == 'getYue') {
            yue = $('.p_zc01').parent().find('h4').html() - 0 || 0.000000001
            var touzi = $('.p_zc02').parent().find('h4').html()
            sendResponse({state: 'getYue:ok', yue: yue, touzi: touzi})
          }
        }
      )
    }
    function isRunning () {
      chrome.runtime.sendMessage({
        action: 'onLoaded',
        isStop: !!isCanuser,
        location: window.location
      },
      function (response) {
        if (response.state == 'onLoaded:ok') {
          console.log('onLoaded:ok', response, 'have:', response.yue, $('.p_zc01').parent().find('h4').html() - 0)
          isLogin = response.isLogin
          loginType = response.loginType || 1
          nativeLogin = response.nativeLogins
          canFlash = response.canFlash
          sendAuto = response.sendAuto
          isTrySub = response.isTrySub
          yue = response.yue
          isloaded = true
          subMin = response.subMin
          if (response.isLogin) {
            isWorking = response.isWorking
            if (yue > youhave) {
              chrome.runtime.sendMessage({ 
                action: 'beginSub',
                type: 2
              },
              function (response) {
              })
            }
            if (isCanuser) {
              initKey($__this)
            }
            addLis()
            if (isWorking) {
              running()
              console.log('插件正在工作。。。')
            }
          } else {
            console.log('插件需要登录后才能工作')
          }
          if (!nativeLogin && response.addr) {
            setTimeout(function () {
              initNativeLogin(response.type, response.addr)
            }, 100)
          }
        }
      })
    }
    function doReflash (time) {
      console.log('window.location.reload')
      setTimeout(function () {
        window.location = window.location
      }, time)
    }
    function running () {
      if (isWorking) {
        console.log('大世界插件正在监听倒计时属性变化', new Date())
        setTimeout(running, 1000)
      }
    }
  })
}, 200)
